package imp.core.basics;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;

import imp.core.basics.gui.ErrorDialog;
import imp.core.data.SessionData;
import imp.core.debug.DebugManager;



/**
 * The Error Handler displays error messages when an error occurred and writes the
 * log file.
 * @author Patrick Arnold
 * @since 08.09.2010
 *
 */
public class ErrorHandler {


	/**
	 * Handles a runtime error, i.e. displays an error message and logs the error. 
	 * @param message The error message which is to be displayed or null, if no error
	 * message is to be displayed.
	 * @param className The name of the class where the error occurred.
	 * @param methodName The name of the method where the error occurred.
	 * @param exception The exception which has been occurred. Null, if there was no java (runtime)
	 * exception.
	 */
	public static void error( String message, String location, Exception exception) {
		
		// Displaying the error message:
		
		message = "<html>Runtime error in module " 
			+ location + "()."
			+ "<br /><br />" + message + "<br /><br /><br /><br /></html>";
		
		String title = "Runtime Error";
		new ErrorDialog( message, title);
		
		
		// Error logging:
		
		if( exception != null) {
			
			Writer result = new StringWriter();
			PrintWriter printWriter = new PrintWriter(result);
			exception.printStackTrace( printWriter);
			
			String exceptionStack = result.toString();
			
			String[] output = { exceptionStack, ""};
			IOManager.write( output, ".log", true);
		}
		
		
		// Debug file:
		
		if( SessionData.isDebugMode()) {
			String[] output = { "Error in Module ", "    " + location };
			DebugManager.displayStringField( output, title);
		}
		
	}
	
	
	
	/**
	 * Returns the name of the method which is currently executed.
	 * @return The name of the method which is not currently executed. This is NOT this method,
	 * but whatever method has called it.
	 */
	public static String getParserLocation() { 
	
		StackTraceElement stackTraceElements[] = ( new Throwable()).getStackTrace(); 
		return stackTraceElements[1].toString(); 
	
	}
	
	
	
}
